package com.example.xd.model_video.clipvideo;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.xd.model_video.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by RWL on 2018/4/2.
 * 通用帧列表Adapter
 */

public class VideoEditAdapter extends RecyclerView.Adapter {

    private static final String TAG = VideoEditAdapter.class.getSimpleName();
    private static final int LEFT = 0x16;
    private static final int RIGHT = 0x18;

    private List<VideoEditInfo> lists = new ArrayList<>();
    private List<VideoEditInfo> showLists = new ArrayList<>();
    private LayoutInflater inflater;

    private long clipStart = 0, clipEnd;
    private int itemW;
    private int leftItemW;
    private int rightItemW;
    private static int RIGHT_MAX_ITEMW;
    private int startPosition = 0;
    private int endPosition = 0;
    private int onTouchItem = 0x0;
    private Context context;
    private ViewGroup parent;
    private int totalWidth = 0;

    private float pictureRate;

    //单位宽度，即该段视频MultVideoRangeSeekBar平均1s对应的宽度，单位px
    private float unitWidth;

    public VideoEditAdapter(Context context, int itemW) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.itemW = itemW;
        this.leftItemW = itemW;
        this.rightItemW = itemW;
    }

    public VideoEditAdapter(Context context, int itemW, float pictureRate){
        this(context, itemW);
        this.pictureRate = pictureRate;
    }

    public void setDuration(long duration){
        this.clipEnd  = (long) (duration / (1000 * pictureRate));
        double i = duration / pictureRate;
        i = i * itemW;
        i = i % itemW;
        rightItemW = (int) Math.round(i);
        if(rightItemW == 0)
            rightItemW = itemW;
        RIGHT_MAX_ITEMW = rightItemW;
        lists.addAll(Arrays.asList(new VideoEditInfo[(int) Math.ceil(duration * 1.0f / pictureRate)]));
        showLists.addAll(Arrays.asList(new VideoEditInfo[(int) Math.ceil(duration * 1.0f / pictureRate)]));
        int total = getTotalWidth();
        unitWidth = 1.0f * total * 1000 / duration;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        this.parent = parent;
        return new EditViewHolder(inflater.inflate(R.layout.video_item, parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        EditViewHolder viewHolder = (EditViewHolder) holder;

        String file = "file://";
        if(showLists.get(position) != null)
            file += showLists.get(position).path;
        Glide.with(context)
                .load(file)
                .diskCacheStrategy( DiskCacheStrategy.RESULT )
                .into(viewHolder.img);

        ViewGroup.LayoutParams layoutParams =  ((EditViewHolder) holder).layout.getLayoutParams();
        layoutParams.height = (int) (itemW * (9.0f / 16));

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) ((EditViewHolder) holder).img.getLayoutParams();
        if(position != 0 && position != showLists.size() -1 ){
            layoutParams.width = itemW;
            params.gravity = Gravity.CENTER;
            ((EditViewHolder) holder).layout.setLayoutParams(layoutParams);
            ((EditViewHolder) holder).img.setLayoutParams(params);
        } else {
            if(position == 0){
                layoutParams.width = leftItemW;
                params.gravity = Gravity.END;
                ((EditViewHolder) holder).layout.setLayoutParams(layoutParams);
                ((EditViewHolder) holder).img.setLayoutParams(params);
            }
            if(position == showLists.size() - 1){
                layoutParams.width -= (itemW - rightItemW);
                params.gravity = Gravity.START;
                ((EditViewHolder) holder).layout.setLayoutParams(layoutParams);
                ((EditViewHolder) holder).img.setLayoutParams(params);
            }
        }
        if(onTouchItem != 0x0){
            params.gravity = onTouchItem == LEFT ? Gravity.END : Gravity.START;
            ((EditViewHolder) holder).img.setLayoutParams(params);
        }
    }

    @Override
    public int getItemCount() {
        return showLists.size();
    }

    private final class EditViewHolder extends RecyclerView.ViewHolder {
        ImageView img;
        LinearLayout layout;

        EditViewHolder(View itemView) {
            super(itemView);
            img = (ImageView) itemView.findViewById(R.id.id_image);
            layout = (LinearLayout) itemView.findViewById(R.id.id_layout);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) img.getLayoutParams();
            layoutParams.width = itemW;
            img.setLayoutParams(layoutParams);
            setIsRecyclable(false);
        }
    }

    public void addItemVideoInfo(VideoEditInfo info) {
        if(lists.size() > endPosition) {
            lists.set(endPosition, info);
            showLists.set(endPosition, info);
        } else {
            lists.add(endPosition, info);
            showLists.add(endPosition, info);
        }
        notifyItemChanged(endPosition);
        endPosition++;
    }

    public void setRange(float start, float end){
        double i = start / pictureRate;
        double j = end / pictureRate;
        int startIndex = (int) Math.floor(i), endIndex = (int) Math.floor(j);
        leftItemW = (int) ( itemW * (startIndex + 1 - i));
        rightItemW = (int) ( itemW * (endIndex - j));
        if(rightItemW == 0)
            rightItemW = itemW;
        showLists.clear();
        for(int index = startIndex; index <= endIndex; index++){
            if(index >= lists.size())
                break;
            showLists.add(lists.get(index));
        }
        startPosition = startIndex;
        endPosition = endIndex;
        notifyDataSetChanged();
//        notifyItemRangeChanged(startIndex, endIndex - startIndex + 1);
    }

    public void dragItem(int direction, int dx){
        int position;
        onTouchItem = direction;
        while(dx > itemW || dx < -itemW){
            dragItem(direction, dx >0 ? itemW : - itemW);
            dx -= dx >0 ? itemW : - itemW;
        }
        boolean isNew = true;
        if (direction == LEFT){
            position = 0;
            leftItemW -= dx;
            isNew = false;
            if(leftItemW <= 0 && endPosition != startPosition){
                leftItemW += itemW;
                showLists.remove(position);
                this.notifyItemRemoved(position);
                startPosition++;
                isNew = true;
            } else if(leftItemW > itemW && startPosition != 0){
                leftItemW -= itemW;
                showLists.add(0, lists.get(--startPosition));
                isNew = true;
            } else if(showLists.size() == 1 && leftItemW > rightItemW && startPosition != 0){
                leftItemW -= rightItemW;
                showLists.add(0, lists.get(--startPosition));
                isNew = true;
            } else if(leftItemW > itemW && startPosition == 0){
                leftItemW = itemW;
                isNew = false;
            }
        } else {
            position = showLists.size() - 1;
            rightItemW += dx;
            isNew = false;
            if(rightItemW <= 0 && endPosition != startPosition){
                rightItemW += itemW;
                showLists.remove(position);
                this.notifyItemRemoved(position);
                endPosition--;
                isNew = true;
            } else if (rightItemW > itemW && endPosition != lists.size()){
                rightItemW -= itemW;
                showLists.add(lists.get(endPosition++));
                isNew = true;
            } else if(showLists.size() == 1 && rightItemW > leftItemW && startPosition != 0){
                rightItemW -= leftItemW;
                showLists.add(0, lists.get(endPosition++));
                isNew = true;
            } else if(rightItemW > RIGHT_MAX_ITEMW && endPosition == lists.size()){
                rightItemW = RIGHT_MAX_ITEMW;
                isNew = false;
            }
        }
        if(isNew)
            this.notifyDataSetChanged();
        else{
            this.notifyItemChanged(position);
        }
//        if(showLists.size() == 1){
//            leftItemW = leftItemW > rightItemW ? rightItemW : leftItemW;
//            rightItemW = leftItemW > rightItemW ? rightItemW : leftItemW;
//        }
    }

    public void setLeftItemW(int leftItemW) {
        this.leftItemW = leftItemW;
    }

    public void setRightItemW(int rightItemW) {
        this.rightItemW = rightItemW;
    }

    public int getTotalWidth(){
        if(showLists.size() == 0 || showLists == null)
            return 0;
        else if(showLists.size() == 1)
            return leftItemW > rightItemW ? rightItemW : leftItemW;
        else if(showLists.size() == 2)
            return leftItemW + rightItemW;
        else
            return itemW *(showLists.size() - 2) + leftItemW + rightItemW;
    }

    public float getUnitWidth() {
        return unitWidth;
    }
}
